package com.example.simin_manage.admim.controller;

import com.example.simin_manage.admim.dto.Response;

import com.example.simin_manage.admim.dto.UserWithDept;
import com.example.simin_manage.controller.UserController;
import com.example.simin_manage.dto.LoginRequest;
import com.example.simin_manage.dto.UserResponse;
import com.example.simin_manage.entity.SysDept;
import com.example.simin_manage.entity.SysUser;
import com.example.simin_manage.mapper.DeptMapper;
import com.example.simin_manage.mapper.SysUserMapper;
import com.example.simin_manage.service.UserService;
import com.example.simin_manage.util.HashUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: panpan
 * @time: 2025/9/14
 */
@RestController
@RequestMapping("/api/admin")
public class AdminController {

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Response login(@RequestBody LoginRequest request, HttpServletRequest httpRequest) {
        SysUser user = userService.login(request);
        if (user != null) {
            // 登录成功，将用户 id 写入 session
            httpRequest.getSession().setAttribute("userId", user.getId());
            httpRequest.getSession().setAttribute("username", user.getUsername());
            return new Response(200, "登录成功", null);
        } else {
            return new Response(401, "用户名或密码错误", null);
        }
    }


    // 查询所有用户
    @GetMapping("/users")
    public Response getAllUsers() {
        List<UserWithDept> users = userMapper.selectAllUsersWithDept();
        return new Response(200, "查询成功", users);
    }


    /********** 查询用户（模糊查询） **********/
    @GetMapping("/users/search")
    public Response searchUsers(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String role,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String deptId
    ) {
        // keyword 可以匹配昵称、用户名
        List<UserWithDept> users = userMapper.selectUsersByFilters(keyword, role, status, deptId);
        return new Response(200, "查询成功", users);
    }


    // 新增用户
    @PostMapping("/users")
    public Response addUser(@RequestBody SysUser user) {
        user.setPassword(HashUtil.sha256(user.getPassword())); // 默认加密
        user.setCreateTime(LocalDateTime.now());
        userMapper.insert(user);
        return new Response(200, "新增成功", null);
    }
    @GetMapping("/adminusers/{id}")
    public Response getUser(@PathVariable Long id) {
        SysUser user = userMapper.selectById(id);
        if(user == null) return new Response(404, "用户不存在", null);
        return new Response(200, "查询成功", user);
    }

    // 更新用户
    @PutMapping("/adminusers/{id}")
    public Response updateUser(@PathVariable Long id, @RequestBody SysUser user) {
        System.out.println("PUT 请求到达 updateUser, id=" + id + ", body=" + user);

        SysUser dbUser = userMapper.selectById(id);
        if (dbUser == null) {
            return new Response(404, "用户不存在", null);
        }

        dbUser.setNickname(user.getNickname());
        dbUser.setStatus(user.getStatus());
        dbUser.setDeptId(user.getDeptId());
        dbUser.setRole(user.getRole());
        dbUser.setUpdateTime(LocalDateTime.now());

        int rows = userMapper.updateById(dbUser);

        // ⚡ deptName 不保存数据库，只是返回给前端显示
        dbUser.setDeptName(user.getDeptName());

        if (rows > 0) {
            return new Response(200, "修改成功", dbUser);
        } else {
            return new Response(500, "修改失败，数据库未更新", null);
        }
    }


    // 删除用户
    @DeleteMapping("/users/{id}")
    public Response deleteUser(@PathVariable Long id) {
        userMapper.deleteById(id);
        return new Response(200, "删除成功", null);
    }

    // 重置密码
    @PutMapping("/users/{id}/reset-password")
    public Response resetPassword(@PathVariable Long id, @RequestBody Map<String, String> body) {
        String newPwd = body.get("password");
        if (newPwd == null || newPwd.isEmpty()) return new Response(400, "密码不能为空", null);
        SysUser user = userMapper.selectById(id);
        if (user == null) return new Response(404, "用户不存在", null);
        user.setPassword(HashUtil.sha256(newPwd));
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateById(user);
        return new Response(200, "密码已重置", null);
    }
}
